import { Inject } from '../decorates/inject';
import { AEditorBase } from './editor-base';
import { Factory } from '../utils/factory';
import { ZExcel } from '../init';
import { Events } from './events';
import { Config } from './config';
import { ICellBase } from '../interfaces/cell';

@Inject()
export class EditorManage {
    containerId: string;
    editorContainer: HTMLElement;
    protected editors: Map<string, AEditorBase> = new Map();
    constructor(protected events: Events, protected conf: Config) {
        
    }
    public zInit() {
        this.createEditorContainer();
        this.events.clickEvt.subscribe(ev => {

        });
        this.events.dbclickEvt.subscribe(ev => {
            this.openEditor(ev.detail.cell)
        });
    }
    public openEditor(cell: ICellBase) {
        let editor = this.editors.get(cell.editor);
        if(editor == undefined) return;
        editor.open(cell);
    }
    protected createEditorContainer() {
        let ele = document.createElement('div');
        ele.setAttribute('class', 'z-excel-editor-container');
        let container = document.querySelector('#'+this.containerId) as HTMLElement;
        this.editorContainer = ele;
        // bind event and stop stopPropagation
        this.editorContainer.addEventListener('click', this.stopPropagation);
        this.editorContainer.addEventListener('mousedown', this.stopPropagation);
        this.editorContainer.addEventListener('mouseup', this.stopPropagation);
        this.editorContainer.addEventListener('mousemove', this.stopPropagation);
        container.append(ele);
    }
    private stopPropagation(ev: Event) {
        ev.cancelBubble = true;
        ev.stopPropagation();
    }
    public loadEditor(editor: { new(): AEditorBase}) {
        let editorInstance = this.resolveDepents<AEditorBase>(editor);
        this.editors.set(editorInstance.editorName, editorInstance);
    }
    private resolveDepents<T = any>(cls: { new(...params: any[]): T}) {
        let types = (<any>Reflect).getMetadata("design:paramtypes", cls);
        try {
            for(let i = 0; i < types.length; i++) {
                if(Object.prototype.toString.call(types[i]) == '[object Function]') {
                    let tempInstance = ZExcel.instance.get(this.containerId).classes.get(types[i].prototype.constructor.name);
                    if(tempInstance == undefined) {
                        types[i] = this.resolveDepents(types[i]);
                    }else{
                        types[i] = tempInstance;
                    }
                }
            }        
        } catch (error) {
            
        }
        return new cls(...types);
    }
}